package com.atguigu.config;

import com.atguigu.pojo.User;
import com.atguigu.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义的 UserRealm
 *
 * @author sx
 * @date 2022-02-23 13:00
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行=》授权 doGetAuthorizationInfo");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //授权
//        info.addStringPermission("user:add");

        //拿到当前登录对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();

        //设置当前用户的权限(数据库加字段)
        info.addStringPermission(currentUser.getPerms());

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行=》认证 doGetAuthenticationInfo");

        //从数据库获取 username\password
//        String username = "root";
//        String password = "root";


        //获取前端输入的，账号密码加密后的token
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        //从数据库中查询
        User user = userService.queryUserByName(token.getUsername());

        if (user == null){
            return null;
        }

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("loginUser",user);

        //密码认证，shiro做 , 可以 MD5加密
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }

}
